#!/usr/bin/groovy
/*
Deploy micro-service based on charts
Example call:

def name = 'mobtech'
def ns = 'saas'
def node_label = 'cd4mobtech'
def image_tag = '200316_1338-e49e40f'

Expected configures:
- node_label: label of jenkins slave node to run this job
- name: will be used as default deployment name and chart name if not provided
- deploy_name: deployment name for helm chart
- ns: k8s namespace to deploy chart to
- chart_dir: chart name in baas-ops repo
- set: additional setting for helm install
- repo: for chart url
- chartRepoAuth: for chart repo auth
*/

def call(Map config){
    def ppl = new com.mobtech.ci.Pipeline()
    if (!config.repo) {
        config.repo = "http://charts.ops.svc"
    }
    //node("${config.node_label}") {
        stage("Deploy ${config.deploy_name?:config.name}") {
            println "DEBUG: deploy config: ${config}"
            println "DEBUG: deploy chart : ${config.repo}/${config.chart_name?: config.name}"
            // Per https://github.com/kubernetes-helm/chartmuseum, repo add is required to get index.yaml
            // 添加自己的chart仓库
            withCredentials([usernamePassword(credentialsId: config.chartRepoAuth, passwordVariable: 'chartRepoPass', usernameVariable: 'chartRepoUser')]) {
                sh "helm repo add mob ${config.repo} --username ${env.chartRepoUser} --password ${env.chartRepoPass}"
            }
            // Since helm v3，need to create Namespace
            sh "kubectl get ns |grep -w ^${config.ns} &>/dev/null || kubectl create ns ${config.ns}"
            // Start to deploy chart
            ppl.helmDeploy(
                    dry_run       : false,
                    name          : config.deploy_name?:config.name,
                    namespace     : config.ns,
                    version       : config.version,
                    // repo          : config.repo,
                    chart_dir     : "mob/${config.chart_name?: config.name}",
                    set           : config.set)
            if (config.wait) {
                timeout(time: config.timeout?:600, unit: 'SECONDS') {
                    // wait for sts or deployment deployed
                    // item should be something like 'deploy/violin' or 'sts/peer'
                    for (def item in config.wait) {
                       sh "/usr/bin/kubectl -n ${config.ns} rollout status ${item}"
                    }
                }
            }
        }
    //}
}
